package com.ls.lserp.modules.trade.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.CustomizationContract;
import com.ls.lserp.modules.sys.entity.SendEmailMessage;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.trade.entity.CartonInfo;
import com.ls.lserp.modules.trade.entity.CustomEnchase;
import com.ls.lserp.modules.trade.entity.Enchase;
import com.ls.lserp.modules.trade.service.CustomEnchaseService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: EnchaseController
 * @Description: 装箱单
 * 
 * @author
 * @date 2017年3月24日 下午18:40:00
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/customenchase/single")
public class CustomEnchaseController extends BaseController {

	@Autowired
	// 保存 编辑 删除 方法
	private CustomEnchaseService enchaseService;
	@Autowired
	Configuration freemarkerConfiguration;
	private SXSSFWorkbook tyy = new SXSSFWorkbook ();

	@InitBinder
	public void initBinder(WebDataBinder sBinder) {
		sBinder.setAutoGrowCollectionLimit(20000);
	}
	
	@ModelAttribute
	public CustomEnchase get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return enchaseService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new CustomEnchase();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/trade/customenchase";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param enchase
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(CustomEnchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "enchase");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 箱单号
		searchParam.append("&packageNo=");
		searchParam.append(enchase.getPackageNo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(enchase.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());

		// 查询一览页面数据
		Page<CustomEnchase> page = enchaseService.findList(new Page<CustomEnchase>(request, response), enchase);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("enchases", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("customenchase.ftl"),
				map);
		listMap.put("enchase", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 进入编辑页面
	 * 
	 * @param enchase
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "form")
	public String form(CustomEnchase enchase, RedirectAttributes redirectAttributes, Model model, HttpSession session) {
		if (enchase.getId() != null) {
			
		} else {
			enchase.setGrossWeight((double)0);
			enchase.setNetWeight((double)0);
			enchase.setVolume((double)0);
		}
		model.addAttribute ("customList", enchaseService.findCustomList ());
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("enchase", enchase);

		// 返回页面地址
		return "modules/trade/customenchaseCreate";
	}

	/**
	 * 纸箱选择页面
	 * 
	 * @param cartonInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = "cartonSelect")
	public String cartonSelect(CartonInfo cartonInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		// 查询一览页面数据
		List<CartonInfo> cartonSelectList = enchaseService.findCartonInfoList(cartonInfo);
		cartonInfo.setCartonInfoList(cartonSelectList);

		// 将page值赋值给mvc model层返回jsp页面
		model.addAttribute("cartonInfo", cartonInfo);

		// 返回页面地址
		return "modules/trade/cartonSelect";
	}
	
	/**
	 * 纸箱选择页面
	 * 
	 * @param cartonInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = "makeEnchaseList")
	public String makeEnchaseList(CustomEnchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			if (enchase.getId()==null) {
				// 查询一览页面数据
				enchase = enchaseService.findOrderInfoByDate(enchase,0);
			}else {
				enchase = enchaseService.findOrderInfoByDate(enchase,1);
			}
			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			if (e.getMessage() != null && e.getMessage().indexOf("Info_Incomplete") != -1) {
				model.addAttribute("errorMessage", e.getMessage().replace("Info_Incomplete", ""));
			}else{
				model.addAttribute("errorMessage", SystemMessageUtils.getMessageName("System_error_please_contact_your_administrator"));
			}
			
		}

		// 返回页面地址
		return "modules/trade/customenchaseCreate";
	}
	
	/**
	 * 纸箱选择页面
	 * 
	 * @param cartonInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = "makeEnchaseListShow")
	public String makeEnchaseListShow(CustomEnchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		// 查询一览页面数据
		try {
			enchase = enchaseService.findOrderInfoByDate(enchase,1);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}

		// 将page值赋值给mvc model层返回jsp页面
		model.addAttribute("enchase", enchase);

		// 返回页面地址
		return "modules/trade/customenchaseShow";
	}

	/**
	 * @Title: addExportDetail @Description: 添加出口成品明细 @param @param
	 * handBook @param @param session @param @return @return String @throws
	 */

	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "addCarton")
	public String addCarton(CustomEnchase enchase, HttpServletRequest request, HttpServletResponse response, Model model) {
		try {

			// 查询一览页面数据
			CartonInfo pCartonInfo = new CartonInfo();
			pCartonInfo.setCommaCartonId(enchase.getCommaCartonId());
			List<CartonInfo> returnCartonInfo = enchaseService.findCartonInfoList(pCartonInfo);

			// 添加纸箱信息
			if (!CollectionsUtils.isEmpty(returnCartonInfo)) {
				enchase.setCartonInfoList(returnCartonInfo);
			}
			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/customenchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/customenchaseCreate";
		}

	}


	/**
	 * @Title: addRowPackageDetails @Description: 添加箱单明细 @param @param
	 * enchase @param @param session @param @return @return String @throws
	 */

	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "addRowPackageDetails")
	public String addRowPackageDetails(Enchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {

			Enchase pdInfo = new Enchase();
			// 设定客户合同号
			pdInfo.setCustomerContractNo(enchase.getIndentList().get(0).getCustomerContractNo());
			// 设定客户款号
			pdInfo.setStyleCustomerNo(enchase.getIndentList().get(0).getStyleCustomerNo());
			// 设定净重
			pdInfo.setCartonNetWeight(new BigDecimal("0"));
			// 设定尺码(只显示8个)
			pdInfo.setAllSizeList(enchase.getAllSizeList().subList(0, 8));
			// 箱号是否存在flg
			pdInfo.setHasCartonFromTo("0");
			// 纸箱体积
			pdInfo.setBoxVolume(enchase.getCartonInfoList().get(0).getCartonVolume());
			// 纸箱重量
			pdInfo.setBoxWeight(enchase.getCartonInfoList().get(0).getCartonWeight());

			if (CollectionsUtils.isEmpty(enchase.getPackageDetailsList())) {
				List<Enchase> pEnchaseList = new ArrayList<Enchase>();
				pEnchaseList.add(pdInfo);
				enchase.setPackageDetailsList(pEnchaseList);
			} else {
				enchase.getPackageDetailsList().add(pdInfo);
			}

			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/customenchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/customenchaseCreate";
		}
	}

	/**
	 * @Title: delExportDetail @Description: 删除进口料件明细 @param @param
	 * handBook @param @param model @param @param session @param @return @return
	 * String @throws
	 */

	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "delPackageDetail")
	public String delPackageDetail(Enchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {

			enchase.getPackageDetailsList().remove(enchase.getTrIndex());

			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/customenchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/customenchaseCreate";
		}
	}

	/**
	 * 保存信息
	 * 
	 * @param enchase
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException
	 */
	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(CustomEnchase enchase, HttpServletRequest request, Model model, HttpServletResponse response) throws Exception {

		// 判断id是否为null （判断新建或修改）
		if (enchase.getId() != null) {
			// 编辑数据
			// 判断数据是否删除
			CustomEnchase enchaseNew = get(enchase.getId().toString());
			// 判断数据是否删除
			if (enchaseNew == null || BaseEntity.DEL_FLAG_DELETE.equals(enchaseNew.getDeleteFlag())) {
				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}

			// 排他处理
			if (enchase.getVersion() == get(enchase.getId().toString()).getVersion()) {

				// 版本号加1
				enchase.setVersion(enchase.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
		}

		// 保存基准数据及子项数据
		enchaseService.saveEnchase(enchase);

		//保存成功给指定人员发送邮件
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
        + request.getContextPath() + Global.getAdminPath() + "/customenchase/single/";
        SendEmailMessage sendEmailMessage = new SendEmailMessage();
        sendEmailMessage.setDataTheme(ResourcesUtil.getConfig("erp_send_mail_theme05"));
        sendEmailMessage.setDataMessage(ResourcesUtil.getConfig("erp_send_mail_textMessage05"));
        sendEmailMessage.setDataXXX01(UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
        sendEmailMessage.setDataXXX02(enchase.getPackageNo());
        sendEmailMessage.setDataXXX03(String.valueOf(enchase.getBigCount()+enchase.getSmallCount()));
        sendEmailMessage.setDataXXX04(String.valueOf(enchase.getContractCount()));
        sendEmailMessage.setDataXXX05(String.valueOf(enchase.getGrossWeight()));
        sendEmailMessage.setDataXXX06(String.valueOf(enchase.getNetWeight()));
        sendEmailMessage.setDataXXX07(String.valueOf(enchase.getVolume()));
        sendEmailMessage.setDataXURLX(url);
        sendEmailMessage.setDataYYMMDD01(DateUtils.formatDate(enchase.getCreateDate(), "yyyy-MM-dd").toString());
        //发送邮件
        UserUtils.sendEmail(sendEmailMessage);
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("enchase_create_save_success")));
	}

	/**
	 * 进入查看页面
	 * 
	 * @param enchase
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customenchase:single:view")
	@RequestMapping(value = "show")
	public String show(CustomEnchase enchase, Model model) {


		// 将查询结果赋值mvc model层返回jsp页面
		model.addAttribute("enchase", enchase);

		// 返回页面地址
		return "modules/trade/customenchaseShow";
	}

	/**
	 * 删除信息
	 * 
	 * @param handBook
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 */
	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "delete")
	public String delete(CustomEnchase enchase, HttpServletResponse response) {
		try {
			// 执行逻辑删除方法
			enchaseService.deleteEnchase(enchase);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}

		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("enchase_show_delete_msg")));
	}
	
	/**
	 * 提交装箱单
	 * 
	 * @param handBook
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 */
	@RequiresPermissions("customenchase:single:edit")
	@RequestMapping(value = "commit")
	public String commit(CustomEnchase enchase, HttpServletResponse response) {
		try {
			// 执行逻辑删除方法
			enchaseService.commitEnchase(enchase);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}

		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("enchase_show_commit_msg")));
	}
	
	/**
     * 导出定制项目单耗
     *
     * @param response
     * @param styleOptionEntity
     * @return
     */
    @RequiresPermissions("customenchase:single:view")
    @RequestMapping(value = "exportFile")
    public String exportFile(CustomEnchase enchase, HttpServletResponse response) {
        try {
            SXSSFWorkbook wb = new SXSSFWorkbook ();
            List<CustomEnchase> makeList = enchaseService.makeExportList (enchase, "无大箱");

            // custom_msg04 :定制项目
            new ExportExcel ("装箱单", wb,"装箱单", CustomEnchase.class, 2).setDataList (makeList);
            tyy = wb;
            return renderString (response,"cloud");
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }

        // 提示错误信息
        return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator")));

    }
    
    /**
     * Excel下载
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequiresPermissions("customenchase:single:view")
    @RequestMapping(value = {"makeExportFile"})
    public void makeExportFile(String targetDate,HttpServletResponse response, HttpServletRequest request)
            throws Exception {
    	String fileName = targetDate+"定制装箱单.xlsx";
        response.reset ();
        response.setContentType ("application/octet-stream; charset=utf-8");
        response.setCharacterEncoding ("UTF-8");
        response.setHeader ("Content-Disposition", "attachment; filename=" + new String (fileName.getBytes (), "ISO-8859-1"));
        tyy.write (response.getOutputStream ());
    }
    
    /**
     * 审核页面
     * @param handBook
     * @param model
     * @return
     */
    @RequiresPermissions("purchase:handbook:audit")
    @RequestMapping(value = "audit")
    public String audit(CustomEnchase enchase,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
    	
    	// 履历一览取得
    	AuditInfo auditInfo = new AuditInfo();
    	// 样品生产id
    	auditInfo.setAuditRelateId(enchase.getId());
    	// 阶段（样品)
    	auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_customEnchase"));
    	AuditInfo resultInfo = enchaseService.findAuditInfo(auditInfo);
    	
    	// 待审核状态可以审核
    	if(resultInfo.getAuditStatus()==0){
    		String strWaitAccept = ResourcesUtil.getConfig("reserver_meterial_wait_accept");
    		if(!enchase.getPackageAuditStatus().equals(strWaitAccept)){
    			resultInfo.setAuditStatus(1L);
    		}
    	}
    	
    	// 样品生产id
    	resultInfo.setAuditRelateId(enchase.getId());
    	// 样品需求单号
    	resultInfo.setAuditRelateNo(enchase.getPackageNo());
    	// 阶段
    	resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_customEnchase"));
    	// 核料状态
    	resultInfo.setVersion(enchase.getVersion());
    	
    	// 将实体类值赋给mvc model层返回jsp页面
    	model.addAttribute("auditInfo", resultInfo);
    	
    	// 返回页面地址
    	return "modules/order/auditInfo";
    }

    /**
     * 保存履历信息
     * @param auditInfo
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException 
     */
    @RequiresPermissions("specimen:production:edit")
    @RequestMapping(value = "saveAudit")
    @ResponseBody
    public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
    	
    	// 判断数据是否删除
    	CustomEnchase newEnchase=get(Long.toString(auditInfo.getAuditRelateId()));
    	
    	// 判断数据是否删除
    	if(newEnchase==null || BaseEntity.DEL_FLAG_DELETE.equals(newEnchase.getDeleteFlag())){
    		// 返回提示信息
    		return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
    	}
    	
        // 审核结果已经通过,返回错误提示信息
    	AuditInfo pAuditResult = new AuditInfo();
    	pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
    	pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
    	if(enchaseService.getAuditResult(pAuditResult)>0){
        	// 返回提示信息
            return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
    	}
    	
    	// 排他
    	if(auditInfo.getVersion()==get(Long.toString(auditInfo.getAuditRelateId())).getVersion()){
    		// 版本号加1
    		auditInfo.setVersion(auditInfo.getVersion()+1);
        	
        }else{	
        	// 返回提示信息
            return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
    	
        // 设置采购手册状态
    	if(auditInfo.getAuditResult()==1){
    	  	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
    	}else{
    	   	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
    	}
    	
        // 保存样品数据
    	enchaseService.saveAuditInfo(auditInfo);
    			
    	// 保存成功返回提示信息
        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
    }

}
